import 'dart:io';

import 'package:camera/camera.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:short_video_app/view_model/publish/camera_entity.dart';

import '../../network/base_entity.dart';
import '../../network/http_manager.dart';
import '../../ui/pages/publish/publish_page.dart';
import '../../utils/hud_util.dart';
import '../../utils/navigator_util.dart';

class CameraViewModel extends ChangeNotifier {
  var _image;
  var imagePicker;
  var type;
  var _video;
  CameraEntity? entity;

  CameraViewModel(this.imagePicker);

  get video => _video;

  get image => _image;

  Future<void> setImage() async {
    _image = await imagePicker.pickImage(
        source: ImageSource.camera,
        imageQuality: 50,
        preferredCameraDevice: CameraDevice.rear);
    _video=null;
  }

  Future<void> setVideo() async {
    _video = await imagePicker.pickVideo(
        source: ImageSource.camera,
        // maxDuration: const Duration(hours: 0, minutes: 0, seconds: 15),
        preferredCameraDevice: CameraDevice.rear);
    _image =null;
  }
  Future<void> gotoPushPage(BuildContext context) async {
    Map<String, dynamic> params = {};
    var url = "/commom/file/upload";
    params["appId"] = "X2e7n1GRrQAvxE6c";
    params["businessCode"] = "SKU";
    params["templateId"] = "2";
    if(_video!=null){
      params["file"]=await MultipartFile.fromFile(_video.path,filename: _video.name);

      IBaseEntity? result = await HttpManager.getInstance().request(url: url,params: params);

      if (result?.isSuccess() == true) {
        CameraEntity tempEntity = CameraEntity.fromJson(result?.getData());
        entity = tempEntity;

        NavigatorUtil.push(context,PublishPage(imageurl: entity?.linkUrl));

      } else {
        HudUtil.toast(result?.getMsg() ?? "");
      }

    }
    else if(_image!=null){
      params["file"]= await MultipartFile.fromFile(_image.path,filename: _image.name);
      IBaseEntity? result = await HttpManager.getInstance().request(url: url,params: params,formData: true);

      if (result?.isSuccess() == true) {
        CameraEntity tempEntity = CameraEntity.fromJson(result?.getData());
        entity = tempEntity;
        // debugPrint("-----bbbbb=---${entity?.linkUrl}---");
        NavigatorUtil.push(context,PublishPage(imageurl: entity?.linkUrl));

      } else {
        HudUtil.toast(result?.getMsg() ?? "");
      }

    }
    else{
      HudUtil.toast("照片/视频为空！");
      return;
    }
  }
  void close(BuildContext context) {
    NavigatorUtil.pop(context);
  }
  Future<void> select() async {
    _image = await imagePicker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 50,
        preferredCameraDevice: CameraDevice.rear);
    _video=null;
  }

}
